import { setStore, getStore, removeStore } from '@/libs/store'
import { getUserInfo } from '@/api/user'

export default {
    state: {
        userinfo: null,
        location: {
            longitude: null,    //经度
            latitude: null,	    //纬度
            province: null,     //省
            city: null,		    //市
            district: null,     //区
            township: null,     //街
            adcode: null,	    //编码
            address: null	    //地址
        }
    },

    getters: {
        userinfo: state => state.userinfo,
        location: state => state.location
    },

    mutations: {
        /**
         * 设置用户信息
         */
        SetUserInfo: (state, data) => {
            state.userinfo = data
            setStore({name: 'userinfo', content: data})
        },
        /**
         * 设置地理位置信息
         * GaodeMap.js -> getLocation() 设置
         */
        SetLocation: (state, data) => {
            state.location = Object.assign(state.location, data)
        }
    },

    actions: {
        /**
         * 从数据库中获取用户信息
         * @param {*} param0 
         * @param {*} openid 
         */
        GetUserInfo({ commit, state, dispatch }, openid) {
            return new Promise((resolve, reject) => {
                //从LocalStorage获取
                const user = getStore({name: 'userinfo'})
                
                if(!user) { //从远程获取
                    getUserInfo(openid).then(response => {
                        if(response.data.status === 200) {
                            commit('SetUserInfo', response.data.data)
                            resolve(response.data.data)
                        } else {
                            removeStore({name: 'userinfo'})
                            console.log('远程获取用户信息失败')
                        }
                    }).catch(() => {
                        console.log('远程获取用户信息异常')
                    })
                } else {
                    commit('SetUserInfo', user)
                    resolve(user)
                }
            })

        }
    }
}